import { action, observable } from 'mobx';
import projectServer from '../services/project';
import Base from './base';
import isSuccess from '../utils/error';
import { message } from 'antd';

const {
    getList, getTypes, getStages, getIdentity, saveProject, detail, infoField,
    addCustomStage, deleteStage,
    completeStage, restartStage, completeProject, restartProject,
    addMember, deleteMember, setManager, setHost,
    saveName, saveInfo, addStage
} = projectServer;

const manageProjectApi = {
    completeStage, restartStage, completeProject, restartProject
}

const membersApi = {
    addMember, deleteMember, setManager, setHost
}

export default class ProjectState extends Base {

    constructor(props) {
        super(props);
        // 注入其它需要调用的store
        setTimeout(() => {
            const { chatState, taskState } = props;
            this.chatState = chatState;
            this.taskState = taskState;
        })

    }

    @observable projectList = []; // 左侧项目列表数据
    @observable projectList0 = []; // 未完成项目列表
    @observable projectList1 = []; // 已完成项目列表

    @observable projectTypes = []; // 获取项目类型
    @observable allStages = []; // 项目周期列表

    @observable detailData = undefined;
    @observable projectActiveStageIndex = 0;
    @observable infoField = [];
    @observable identities = [];

    @action.bound
    async getTypes() {
        const res = await getTypes();
        if (isSuccess(res)) {
            this.projectTypes = res.data;
        }
    }

    @action.bound
    async getList(params, callback) {
        const res = await getList(params);
        if (isSuccess(res)) {
            // console.log('---ProjectState getList---', res);
            const list = res.data && Array.isArray(res.data) ? res.data : [];
            callback && callback(list);
            this.projectList = list;
            if (list.length) {
                const projectList0 = [];
                const projectList1 = [];
                list.forEach(l => {
                    l.iscomplete ? projectList1.push(l) : projectList0.push(l);
                });
                this.projectList0 = projectList0;
                // 组内排序由完成时间大到小排序
                let sortProjectList1 = projectList1;
                if (projectList1.length && projectList1.length > 1) {
                    sortProjectList1 = projectList1.concat().sort((a, b) => {
                        return Date.parse(new Date(b.completedtime)) - Date.parse(new Date(a.completedtime));
                    });
                }
                this.projectList1 = sortProjectList1;
            }
        }
    }

    @action.bound
    async getDetail({ projectid, stageid }, onlyRefleshDetail) {
        this.taskState.setStateValue('needRefreshProjectDetail', undefined); // 重置操作
        const res = await detail({ projectid });
        if (isSuccess(res)) {
            // console.log('---ProjectState getDetail---', res);
            if (res.data && res.data.stages && res.data.stages[0]) {
                const { stages, stagedatas, ...others } = res.data;
                const newStages = [];
                stages.forEach(s => {
                    const stage = stagedatas.find(v => v.stageid === s.recid);
                    if (stage) newStages.push({ ...stage, name: s.recname });
                });
                this.detailData = { ...others, stages: newStages, projectid };

                if (!onlyRefleshDetail) {
                    // 默认获取第一个阶段的字段, 传了stageid就表示显示特定的周期字段
                    const { projecttype } = res.data;
                    const sid = stageid || res.data.stages[0].recid;
                    this.getFields(sid, projecttype);
                    if (projecttype === 1 || projecttype === 2) this.getIdentity(sid, projecttype);
                    this.projectActiveStageIndex = 0;
                    if (stageid) {
                        const index = res.data.stages.findIndex(s => s.recid === stageid);
                        this.projectActiveStageIndex = index < 0 ? 0 : index;
                    }
                }

            } else this.detailData = undefined;
        }
    }

    @action.bound
    async getStages(params) {
        const res = await getStages(params);
        if (isSuccess(res)) {
            // console.log('---ProjectState getStages---', res);
            this.allStages = res.data && Array.isArray(res.data) ? res.data : [];
        }
    }

    @action.bound
    async getFields(stageid, projecttype) {
        const res = await infoField({
            projecttype,
            stageid
        });
        if (isSuccess(res)) {
            // console.log('---ProjectState getFields---', res);
            this.infoField = res.data;
        }
    }

    @action.bound
    async getIdentity(stageid, projecttype) {
        const res = await getIdentity({
            projecttype,
            stageid
        });
        if (isSuccess(res)) {
            // console.log('---ProjectState getIdentity---', res);
            this.identities = res.data || [];
        }
    }

    @action.bound
    async saveProject(params, callback) {
        const res = await saveProject(params);
        if (isSuccess(res)) {
            console.log('---ProjectState saveProject---', res);

            // 刷新列表
            this.getList();
            message.success('保存成功');
            callback && callback();
        }
    }

    @action.bound
    async addCustomStage(params, callback) {
        const res = await addCustomStage(params);
        if (isSuccess(res)) {
            callback && callback(res.data);
        }
        return res;
    }

    @action.bound
    async deleteStage(params, callback) {
        const res = await deleteStage(params);
        if (isSuccess(res)) {
            console.log('---ProjectState deleteStage---', res);
            callback && callback(res.data);
        }
    }

    // 项目状态请求接口的通用处理
    @action.bound
    async manageProject({ key, value, index, params }, callback) {
        const res = await manageProjectApi[key](params);
        if (isSuccess(res)) {
            callback && callback();
            // console.log('---manageProject---', key, res);

            if (key === 'completeProject' || key === 'restartProject') {
                this.detailData = { ...this.detailData, iscomplete: value };
            } else { // 阶段状态更新
                // const { stages } = this.detailData;
                // const newStages = stages.concat();
                // const stage = JSON.parse(JSON.stringify(newStages[index]));
                // stage.iscomplete = value;
                // newStages[index] = stage;
                // this.detailData = { ...this.detailData, stages: newStages };
            }
            // 刷新列表
            this.getList();
        }
    }

    // 项目成员请求接口的通用处理
    @action.bound
    async manageMember({ key, params }, callback) {
        const res = await membersApi[key](params);
        if (isSuccess(res)) {
            callback && callback(res.data);
            console.log('---manageMember---', key, res);
            this.getDetail({ projectid: params.projectid }, true);
        }
    }

    @action.bound
    async saveName(params, callback) {
        const res = await saveName(params);
        if (isSuccess(res)) {
            console.log('---ProjectState saveName---', res);
            callback && callback(res.data);
            // 更新detailData
            this.detailData.name = params.projectname;
            // 刷新列表
            this.getList();
        }
    }

    @action.bound
    async saveInfo(params, callback) {
        const res = await saveInfo(params);
        if (isSuccess(res)) {
            console.log('---ProjectState saveInfo---', res);
            callback && callback(res.data);
            // 刷新列表
            // this.getList();
        }
    }

    @action.bound
    async addStage(params, callback) {
        const res = await addStage(params);
        if (isSuccess(res)) {
            console.log('---ProjectState addStage---', res);
            callback && callback(res.data);
            // 刷新列表
            this.getList();
        }
    }
}